package me.zhengjie.modules.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.config.FileProperties;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.LoadFile;
import me.zhengjie.modules.system.repository.FileRepository;
import me.zhengjie.modules.system.service.FileService;
import me.zhengjie.modules.system.service.dto.FileQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.FileMapper;
import me.zhengjie.service.dto.LocalStorageQueryCriteria;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "file")
public class FileServiceImpl implements FileService {

    private final FileProperties properties;
    private final FileRepository fileRepository;
    private final FileMapper fileMapper;

    @Override
    public Object queryAll(FileQueryCriteria criteria, Pageable pageable) {
        Page<LoadFile> page = fileRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(fileMapper::toDto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LoadFile create(String name, MultipartFile multipartFile) {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new BadRequestException("上传失败");
        }
        try {
            name = StringUtils.isBlank(name) ? FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;
            LoadFile loadFile = new LoadFile(
                    file.getName(),
                    name,
                    suffix,
                    file.getPath(),
                    type,
                    FileUtil.getSize(multipartFile.getSize())
            );
            return fileRepository.save(loadFile);
        }catch (Exception e){
            FileUtil.del(file);
            throw e;
        }
    }
}
